package com.sqoop.commons.send.impl;

import com.sqoop.commons.send.IClient;
import com.sqoop.core.destnation.MqMsgDestination;
import com.sqoop.core.msg.MsgDestination;
import com.sqoop.core.request.Request;
import com.sqoop.core.request.Response;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.jms.core.JmsTemplate;

import javax.jms.Destination;

/**
 * Created by zw on 2017/11/6.
 */
public class JmsClient implements IClient {


    private static Logger logger = LogManager.getLogger(JmsClient.class.getName());

    @Override
    public Response send(Request request) {
        MsgDestination destination  = request.getReceiver();
        if (destination instanceof MqMsgDestination){
            MqMsgDestination mqMsgDestination = (MqMsgDestination)destination;
            JmsTemplate jmsTemplate = new JmsTemplate();
            String username = ActiveMQConnection.DEFAULT_USER;
            if (!StringUtils.isEmpty(mqMsgDestination.getUsername())){
                username = mqMsgDestination.getUsername();
            }
            String password = ActiveMQConnection.DEFAULT_PASSWORD;
            if(!StringUtils.isEmpty(mqMsgDestination.getPassword())){
                password = mqMsgDestination.getPassword();
            }
            if (StringUtils.isEmpty(mqMsgDestination.getMqurl())){
                throw new RuntimeException("url is empty!!!");
            }

            ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(username,password,mqMsgDestination.getMqurl());
            connectionFactory.setTrustAllPackages(true);
            jmsTemplate.setConnectionFactory(connectionFactory);
            Destination queuedestination = null;
            //defaultMessageListenerContainer.setDestinationName(receiveInfo.getQueuename());
            if(mqMsgDestination.getQueuetype().equalsIgnoreCase("queue")){
                queuedestination = new ActiveMQQueue(mqMsgDestination.getQueuename());
            }else{
                queuedestination = new ActiveMQTopic(mqMsgDestination.getQueuename());
            }

            jmsTemplate.convertAndSend(queuedestination,request);
        }else {
            logger.error("msg destination error!!! ", request);
            throw new RuntimeException("msg destination error!!!");
        }
        return null;

    }


    public static void main(String[] args) {
        Request   request = new Request();
        MqMsgDestination mqMsgDestination = new MqMsgDestination();
        //mqMsgDestination.setMqurl();
        //mqMsgDestination.setMqurl();

    }


}